package com.github.wxiaoqi.security.biz.modules.merchant.biz;

import java.security.Key;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.github.wxiaoqi.security.biz.common.biz.request.PosLoginReq;
import com.github.wxiaoqi.security.biz.modules.merchant.entity.AppUserToken;
import com.github.wxiaoqi.security.biz.modules.merchant.mapper.AppUserTokenMapper;
import com.github.wxiaoqi.security.biz.util.JwtClaimItems;
import com.github.wxiaoqi.security.biz.util.JwtUtil;
import com.github.wxiaoqi.security.common.biz.BaseBiz;

import lombok.extern.slf4j.Slf4j;

/**
 * pos登录
 *
 * @author admin
 * @email ${email}
 * @date 2019-03-08 15:28:33
 */
@Slf4j
@Service
public class AppUserTokenBiz extends BaseBiz<AppUserTokenMapper,AppUserToken> {
	
	@Autowired
	private AppUserTokenMapper appUserTokenMapper;
	@Autowired
	private FsbpCashierCounterBiz fsbpCashierCounterBiz;
	@Value("${jwt.key}")
    private String jwtKey;
	
	/**
	 * 登录
	 * @param params
	 * @return
	 */
	public Map<String, Object> login(PosLoginReq request) {
		log.info("pos登录。。。{}"+request);
		Map<String, Object> respMap = new HashMap<>();
		String userType = request.getUserType();
		//如果token为空登陆，不为空则判断token是否过期
		Map<String,Object> mapInfo = new HashMap<String,Object>();
		if (StringUtils.isEmpty(request.getToken())) {
			if(StringUtils.hasText(userType)){
				mapInfo = fsbpCashierCounterBiz.queryUserInfo(request);
			}else{
				mapInfo = fsbpCashierCounterBiz.queryCashierUserInfo(request);
			}
			if(null == mapInfo) {
				respMap.put("code", "01");
				respMap.put("msg", "账号不存在或账号密码错误");
				return respMap;
			}
			if (mapInfo.get("code") == "04" || mapInfo.get("code") == "05" || mapInfo.get("code") == "06") {
				respMap.put("status", "405");
				respMap.put("msg", "用户信息不存在");
				return respMap;
			}
		}else {
			//根据token查询记录判断token是否过期
			AppUserToken appUserToken = new AppUserToken();
			AppUserToken appUserToken1 = new AppUserToken();
			appUserToken.setToken(request.getToken());
			List<AppUserToken> apkList = mapper.select(appUserToken);
			if (null != apkList && apkList.size() > 0) {
				appUserToken1 = apkList.get(0);
			}
			if (appUserToken1 == null) {
				respMap.put("code", "03");
				respMap.put("msg", "其他错误");
				return respMap;
			}
			String[] jwtPayLoadArr = new String[0];
			jwtPayLoadArr="PL0".split(",");
			List<JwtClaimItems> jwtClaimItems = new ArrayList<JwtClaimItems>();
			JwtClaimItems jwtClaimItem =new JwtClaimItems();
			jwtClaimItem.setTagKey(jwtPayLoadArr[0]);
			jwtClaimItem.setRealValue(appUserToken1.getUserName());
			Key key=null;
			try {
		        key=JwtUtil.getKey(jwtKey+"SignatureAlgorithmKey.dat");
	        } catch (Exception e) {
	        }
			String jwtStr=null;
		    try {
			    jwtStr=JwtUtil.generateJwt(key, "BP00", "vivebest", "http channel json transfer", 
			    		"goba", JwtUtil.getExpiryDate(2), new Date(), jwtClaimItems);
		    }
		    catch (Exception e){
		    }
			respMap.put("token", jwtStr);
			respMap.put("code", "00");
			respMap.put("msg", "登陆成功");
		}
		
		String[] jwtPayLoadArr = new String[0];
		jwtPayLoadArr="PL0,PL1".split(",");
		List<JwtClaimItems> jwtClaimItems = new ArrayList<JwtClaimItems>();
		if (jwtPayLoadArr.length >0){
			for (int i=0;i<jwtPayLoadArr.length;i++){
			    JwtClaimItems jwtClaimItem =new JwtClaimItems();
            	jwtClaimItem.setTagKey(jwtPayLoadArr[i]);
                if (jwtPayLoadArr[i].equals("PL0")){
                	jwtClaimItem.setRealValue(request.getCounterNo());
                }
                else if (jwtPayLoadArr[i].equals("PL1")){
                	jwtClaimItem.setRealValue(request.getPassword());
                }
			    jwtClaimItems.add(jwtClaimItem);
			}
		}
		Key key=null;
		try {
	        key=JwtUtil.getKey(jwtKey+"SignatureAlgorithmKey.dat");
        } catch (Exception e) {
        }
		String jwtStr=null;
	    try {
		    jwtStr=JwtUtil.generateJwt(key, "BP00", "vivebest", "http channel json transfer", 
		    		"goba", JwtUtil.getExpiryDate(2), new Date(), jwtClaimItems);
	    }
	    catch (Exception e){
	    }
	    //将token跟用户关联
	    respMap.put("token", jwtStr);//token
		respMap.put("secretKey", mapInfo.get("sign"));//密钥
		respMap.put("acceptBizNo", mapInfo.get("acceptBizNo"));//合作平台编号
		AppUserToken appUserToken = new AppUserToken();
		respMap.put("merNo", mapInfo.get("merNo"));//商户号
		if(StringUtils.hasText(userType)){
			respMap.put("merName", mapInfo.get("userName"));//用户名
		}else{
			String counterNo = request.getCounterNo();
			respMap.put("number", counterNo.substring(counterNo.length()-3, counterNo.length()));//商户名
			respMap.put("merName", mapInfo.get("nickName"));//商户名
			respMap.put("nickName", mapInfo.get("nickName"));//终端名
		}
		appUserToken.setUserName(request.getCounterNo());
		AppUserToken appUserInfo = appUserTokenMapper.query(appUserToken);
		appUserToken.setToken(jwtStr);
		Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		String time = formatter.format(date);
		appUserToken.setExpired(time);
		if(null == appUserInfo){
			appUserTokenMapper.insert(appUserToken);
		}else{
			appUserTokenMapper.updateByPrimaryKey(appUserToken);
		}
		respMap.put("code", "00");
		respMap.put("msg", "登陆成功");
		log.info("验证登录信息结束。。。。。{}",respMap);
		return respMap;
	}
	
}